package ds_industry_2025.industry.gy_09.T1

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

import java.text.SimpleDateFormat
import java.util.{Calendar, Properties}

//  todo 数据抽取部分
object t1_count {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t1")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    val conn=new Properties()
    conn.setProperty("user","root")
    conn.setProperty("password","123456")
    conn.setProperty("driver","com.mysql.jdbc.Driver")

    val day=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)


    //  todo 定义抽取数据的方法01  不需要做任何改变的
    def to_hive01(mysqlName:String,odsName:String):Unit={
      spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_industry?useSSL=false",mysqlName,conn)
        .withColumn("etldate",lit(yesterday))
        .write.format("hive").mode("append")
        .partitionBy("etldate").saveAsTable(s"ods.${odsName}")
      println(s"${odsName}写入完成")
    }

    //  todo 定义抽取数据的方法02  需要剔除字段
    def to_hive02(mysqlName: String, odsName: String): Unit = {
      spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_industry?useSSL=false", mysqlName, conn)
        .drop("ProducePrgCode")
        .withColumn("etldate", lit(yesterday))
        .write.format("hive").mode("append")
        .partitionBy("etldate").saveAsTable(s"ods.${odsName}")
      println(s"${odsName}写入完成")
    }

    //  todo 写入数据
    to_hive01("EnvironmentData","environmentdata")
    to_hive01("ChangeRecord","changerecord")
    to_hive01("BaseMachine","basemachine")
    to_hive02("ProduceRecord","producerecord")
    to_hive01("MachineData","machinedata")


    spark.close()
  }

}
